﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using PhotoGallery.Models;
using PhotoGallery.Repositories;

namespace PhotoGallery.Controllers
{
    [Authorize]
    public class AlbumsManagerController : Controller
    {
        private readonly ILogger<AlbumsManagerController> _logger;
        private PhotoGalleryRepository _repo;
        private IMemoryCache _cache;
        private const string _emptPhoto = "http://photogallery-1252912192.file.myqcloud.com/albumEmpty.png";
        private RoleModel _adminList;
        private SelectListItem[] _albumSelectList;
        public AlbumsManagerController(ILogger<AlbumsManagerController> logging,
            PhotoGalleryRepository repo,
            RoleModel adminList,
            IMemoryCache cache)
        {
            _repo = repo;
            _adminList = adminList;
            _logger = logging;
            _cache = cache;
            _albumSelectList = new SelectListItem[] { new SelectListItem() { Text = "公开相册", Value = "0" }, new SelectListItem() { Text = "个人相册", Value = "1"} };

        }

        // GET: AlbumsManager
        public ActionResult Index()
        {
            var albums = _repo.Albums.Where(w => !string.IsNullOrEmpty(w.Name));
            if (_adminList.Roles.Contains(User.Identity.Name))
            {
                return View(albums.ToList());
            }

            return View(albums.Where(w=>w.Owner == User.Identity.Name));
        }

        // GET: AlbumsManager/Details/5
        public ActionResult Details(string id)
        {
            var album = _repo.Albums.FirstOrDefault(w => w.Id == id);
            return View(album);
        }

        // GET: AlbumsManager/Create
        public ActionResult Create()
        {
            ViewBag.AlbumTypeSelects = new List<SelectListItem>(_albumSelectList);
            return View();
        }

        // POST: AlbumsManager/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(AlbumInfoModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    ModelState.AddModelError("AlbumsManagerFrom", "填写错误");
                    return View(model);
                }
                model.Id = Guid.NewGuid().ToString();
                model.CreateDate = DateTime.Now;
                model.Owner = User.Identity.Name;
                _repo.Albums.Add(model);
                if (_repo.SaveChanges() > 0)
                {
                    _cache.Remove(CacheKeys.AllAlbumsKey);

                }
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: AlbumsManager/Edit/5
        public ActionResult Edit(string id)
        {
            var album = _repo.Albums.FirstOrDefault(w => w.Id == id);
            if (album == null)
            {
                ModelState.AddModelError("AlbumsManagerFrom", "相册不存在");                
                return View(new AlbumInfoModel());
            }
            var albumTypeSelectList = new List<SelectListItem>(_albumSelectList);
            for (var i = 0; i < albumTypeSelectList.Count; i++)
            {
                var item = albumTypeSelectList[i];
                if (item.Value == album.AlbumType.ToString())
                {
                    item.Selected = true;
                    break;
                }
            }
            ViewBag.AlbumTypeSelects = albumTypeSelectList;
            return View(album);
        }

        // POST: AlbumsManager/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(string id, AlbumInfoModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    ModelState.AddModelError("AlbumsManagerFrom", "填写错误");
                    return View(model);
                }
                
                var album = _repo.Albums.FirstOrDefault(w => w.Id == id);
                if (album == null)
                {
                    ModelState.AddModelError("AlbumsManagerFrom", "相册不存在");
                    return View(model);
                }
                album.IsPublic = model.IsPublic;
                album.Name = model.Name;
                album.Owner = model.Owner;
                album.Password = model.Password;
                album.AlbumPath = model.AlbumPath;
                album.AlbumType = model.AlbumType;
                album.CoverPhoto = model.CoverPhoto;
                album.Description = model.Description;
                _repo.Albums.Update(album);
                if (_repo.SaveChanges() > 0)
                {
                    _cache.Remove(CacheKeys.AllAlbumsKey);

                }

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: AlbumsManager/Delete/5
        public ActionResult Delete(string id)
        {
            var album = _repo.Albums.Where(w => w.Id == id).FirstOrDefault();
            if(album == null)
            {
                return RedirectToAction(nameof(Index),new { Msg = "相册不存在"});
            }
            return View(album);
        }

        // POST: AlbumsManager/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(string id, AlbumInfoModel model)
        {
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var album = _repo.Albums.Where(w => w.Id == id).FirstOrDefault();
                    if(album != null)
                    {
                        _repo.Albums.Remove(album);
                        if (_repo.SaveChanges() > 0)
                        {
                            _cache.Remove(CacheKeys.AllAlbumsKey);

                        }
                    }
                    

                }

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}